package com.sihai.ehr.web.action.train;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.AdministrationEvectionApplyForm;
import com.sihai.ehr.model.biz.AuditType;
import com.sihai.ehr.model.biz.Duty;
import com.sihai.ehr.model.biz.EmployeeinfoWork;
import com.sihai.ehr.model.biz.TrainCategory;
import com.sihai.ehr.model.biz.TrainClassroom;
import com.sihai.ehr.model.biz.TrainLecturer;
import com.sihai.ehr.model.biz.TrainMaterResource;
import com.sihai.ehr.model.biz.TrainOutingPlanCloseAuditing;
import com.sihai.ehr.model.biz.TrainPlan;
import com.sihai.ehr.model.biz.TrainPlanAuditing;
import com.sihai.ehr.model.biz.TrainPlanDutyTarget;
import com.sihai.ehr.model.biz.TrainPlanEmployeeTarget;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.service.DutyService;
import com.sihai.ehr.service.EmployeeService;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.service.TrainCategoryService;
import com.sihai.ehr.service.TrainClassroomService;
import com.sihai.ehr.service.TrainLecturerService;
import com.sihai.ehr.service.TrainMaterResourceService;
import com.sihai.ehr.service.TrainPlanEmployeeTargetService;
import com.sihai.ehr.service.TrainPlanService;
import com.sihai.ehr.utils.StringUtil;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.StaffSearchPojo;
import com.sihai.ehr.web.pojo.TrainPlanEmployeeTargetPojo;

/**
 * 培训计划控制器
 * 
 * @author henry
 * 
 */
@Results({
		@Result(name = "main", location = "train_main.jsp"),
		@Result(name = "outing_train_manage", location = "outing_train_manage.jsp"),
		@Result(name = "outing_train_list", location = "outing_train_list.jsp"),
		@Result(name = "outing_train_target_sel_main", location = "outing_train_target_sel_main.jsp"),
		@Result(name = "outing_train_target_sel_list", location = "outing_train_target_sel_list.jsp"),
		@Result(name = "outing_train_list_audit", location = "outing_train_list_audit.jsp"),
		@Result(name = "outing_train_close_list_audit", location = "outing_train_close_list_audit.jsp"),
		@Result(name = "outing_train_audit", location = "outing_train_audit.jsp"),
		@Result(name = "outing_train_close_audit", location = "outing_train_close_audit.jsp"),
		@Result(name = "plan_list_browse", location = "plan_list_browse.jsp") })
public class TrainOutPlanAction extends EHRAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Log log = LogFactory.getLog(TrainOutPlanAction.class);

	@BeanInject
	private OrganizationService organizationService;
	@BeanInject
	private DutyService dutyService;
	@BeanInject
	private EmployeeService employeeService;
	@BeanInject
	private TrainPlanService trainPlanService;
	@BeanInject
	private TrainCategoryService trainCategoryService; // 培训类型服务
	@BeanInject
	private TrainClassroomService trainClassroomService; // 培训室服务
	@BeanInject
	private TrainLecturerService trainLecturerService; // 培训讲师服务
	@BeanInject
	private TrainPlanEmployeeTargetService trainPlanEmployeeTargetService; // 培训计划员工选择对象服务
	@BeanInject
	private TrainMaterResourceService trainMaterResourceService; // 培训资源服务

	private List<Organization> organizations;
	private LimitedList<TrainPlan> plans;
	private LimitedList<TrainCategory> categories;
	private LimitedList<TrainLecturer> lecturers;
	private LimitedList<TrainClassroom> classrooms;
	private TrainPlan plan;
	private Long planId;
	private String ids;
	private Long dutyId;
	private Duty duty;
	private LimitedList<EmployeeinfoWork> works;
	// 培训职务对象
	private LimitedList<TrainPlanEmployeeTarget> employeeTargets;

	// -----------------培训计划申请审核模块-----------------
	private List<List<TrainPlanAuditing>> audits;
	private List<List<TrainOutingPlanCloseAuditing>> outingAudits;
	/** 功能模块 */
	private String module;

	@Action("/train/outing_train_main")
	@Override
	public String execute() throws Exception {
		listTitle = "外训申请";
		listAction = "/train/outing_train_list.xhtml";
		organizations = organizationService
				.findChildren(null, true, null, null);
		if (organizations != null && organizations.size() > 0) {
			if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
			organizationId = organizations.get(0).getId();
		}
		showChildOrg = true;
		return "main";
	}

	@Action("/train/outing_train_list")
	public String list() {
		listAction = "/train/outing_train_list.xhtml";
		plans = trainPlanService.getTrainPlans(organizationId, dutyId, 1,
				AuditStatus.wait_audit, createLimit(), createSorter());
		paging(plans);
		/* 设置翻页action */
		this.setPageUrl("train/outing_train_list.xhtml");
		return "outing_train_list";
	}

	// 审核
	@Action("/train/outing_audit_main")
	public String executePlanAudit() throws Exception {
		listTitle = "外训审核 - 审核";
		listAction = "/train/outing_train_list_audit.xhtml";
		organizations = organizationService
				.findChildren(null, true, null, null);
		if (organizations != null && organizations.size() > 0) {
			if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
			organizationId = organizations.get(0).getId();
		}
		showChildOrg = true;
		return "main";
	}

	@Action("/train/outing_train_list_audit")
	public String dispatchPlanAuditList() {
		listAction = "/train/outing_train_list_audit.xhtml";
		plans = trainPlanService.getTrainPlans(organizationId, dutyId, 1, null,
				createLimit(), createSorter());
		paging(plans);
		/* 设置翻页action */
		this.setPageUrl("train/outing_train_list_audit.xhtml");
		return "outing_train_list_audit";
	}

	// ////////////////////////////////

	/**
	 * 转向培训计划设置处理
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/train/outing_train_manage")
	public String dispatchPlan() throws Exception {
		boolean isFirst = getParameter("p") == null ? false : true;
		if (planId == null || planId <= 0) {
			// 添加
			plan = new TrainPlan();
			plan.setOrganization(organizationService.get(organizationId));
		} else {
			// 修改
			plan = trainPlanService.getTrainPlan(planId);
			if (plan.getOrganization().getTopOrganization() == null) {
				organizationId = plan.getOrganization().getId();
			} else {
				organizationId = plan.getOrganization().getTopOrganization()
						.getId();
			}
		}

		HttpSession session = ServletActionContext.getRequest().getSession();
		Object obj = session.getAttribute("current_plan_form");
		if (obj != null) {
			plan = (TrainPlan) obj;
			session.removeAttribute("current_plan_form");
		}

		// 培训类别
		categories = trainCategoryService.getTrainCategories(organizationId,
				null, null);
		employeeTargets = new LimitedList<TrainPlanEmployeeTarget>();
		// 读取培训职务对象列表
		// 检测是否已经选择对象返回
		boolean isHasSelectObject = false;
		List<TrainPlanEmployeeTargetPojo> employeeTargetPojos = new ArrayList<TrainPlanEmployeeTargetPojo>();
		
		if (!isFirst) {
			if(session.getAttribute("duty_outing_target") != null){
				employeeTargetPojos = (List<TrainPlanEmployeeTargetPojo>)session.getAttribute("duty_outing_target");
				if(employeeTargetPojos != null && employeeTargetPojos.size() > 0){
					Iterator<TrainPlanEmployeeTargetPojo> it = employeeTargetPojos.iterator();
					while(it.hasNext()){
						TrainPlanEmployeeTargetPojo employeeTargetPojo = it.next();
						TrainPlanEmployeeTarget employeeTarget = new TrainPlanEmployeeTarget();
						employeeTarget.setOrganization(organizationService.get(employeeTargetPojo.getOrganizationId()));
						employeeTarget.setDuty(dutyService.get(employeeTargetPojo.getDutyId()));
						employeeTarget.setEmployeeinfoWork(employeeService.getEmployeeinfoWork(employeeTargetPojo.getWorkId()));
						employeeTargets.add(employeeTarget);
					}
				}
//				employeeTargets = (LimitedList<TrainPlanEmployeeTarget>) session.getAttribute("duty_outing_target");
				isHasSelectObject = true;
			}
		}else{
			session.removeAttribute("duty_outing_target");
		}
		if (!isHasSelectObject) {
			employeeTargets = trainPlanEmployeeTargetService
					.getTrainPlanEmployeeTargets(planId, null, null);
			if(employeeTargets != null && employeeTargets.size() > 0){
				Iterator<TrainPlanEmployeeTarget> it = employeeTargets.iterator();
				while(it.hasNext()){
					TrainPlanEmployeeTarget employeeTarget = it.next();
					TrainPlanEmployeeTargetPojo employeeTargetPojo = new TrainPlanEmployeeTargetPojo();
					employeeTargetPojo.setOrganizationId(employeeTarget.getOrganization().getId());
					employeeTargetPojo.setDutyId(employeeTarget.getDuty().getId());
					employeeTargetPojo.setWorkId(employeeTarget.getEmployeeinfoWork().getId());
					employeeTargetPojo.setWorkName(employeeTarget.getEmployeeinfoWork().getBaseId().getName());
					employeeTargetPojos.add(employeeTargetPojo);
				}
				session.setAttribute("duty_outing_target", employeeTargetPojos);
			}
		}
		return "outing_train_manage";
	}

	/**
	 * 选择培训目标
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/train/outing_train_target_sel_main")
	public String dispatchPlanTarget() throws Exception {
		listAction = "/train/outing_train_target_sel_list.xhtml";
		listTitle = "外训申请 - 培训对象选择";
		module = "outing_train_list";
		return "outing_train_target_sel_main";
	}

	@Action("/train/outing_train_target_sel_list")
	public String dispatchTargetList() throws Exception {
		if (dutyId == null || dutyId < 0) {
			if (duty == null) {
				duty = new Duty();
			}
			Organization o = new Organization();
			o.setId(organizationId);
			duty.setOrganization(o);

			List<Duty> duties = dutyService.search(duty, createLimit(),
					createSorter());
			if (duties != null && duties.size() > 0) {
				dutyId = duties.get(0).getId();
			}
		}
		StaffSearchPojo search = new StaffSearchPojo();
		search.setDepartment(organizationId);
		search.setDuty(dutyId == null ? 0 : dutyId);

		this.setSortProperty("id");
		this.setSortType("asc");
		works = employeeService.searchEmployeeinfoWorks(search, organizationId,
				"1", createLimit(), createSorter());
		// 分页
		this.paging(works);
		/* 设置翻页action */
		this.setPageUrl("train/outing_train_target_sel_list.xhtml");

		return "outing_train_target_sel_list";
	}

	/**
	 * 提交培训计划
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/train/post_outing_train_plan")
	public String postOutingTrainPlan() throws Exception {
		//
		if (plan == null) {
			if (log.isErrorEnabled()) {
				log.error("提交数据为空");
				return ERROR;
			}
		}
		if (plan.getId() == null) {
			// 添加
		} else {
			// 修改
		}
		plan.setLecturerType(1); // 外训
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		plan.setPlanStartDate(formatter.parse(getParameter("planStartDate")));
		plan.setPlanEndDate(formatter.parse(getParameter("planEndDate")));
		plan.setTrainStartDate(formatter.parse(getParameter("planStartDate")));
		plan.setTrainEndDate(formatter.parse(getParameter("planEndDate")));
		/*String strDutyTargetParam = getParameter("duty_outing_target") == null ? ""
				: getParameter("duty_outing_target");
		if (strDutyTargetParam.startsWith("\"")) {
			strDutyTargetParam = strDutyTargetParam.substring(1,
					strDutyTargetParam.length() - 1);
		}
		String jsonEmployeeTargets = strDutyTargetParam.isEmpty() ? "[]" : "["
				+ strDutyTargetParam + "]";*/
		HttpSession session = ServletActionContext.getRequest().getSession();
		List<TrainPlanEmployeeTargetPojo> employeeTargetPojos = new ArrayList<TrainPlanEmployeeTargetPojo>();
		if(session.getAttribute("duty_outing_target") != null){
			employeeTargetPojos = (List<TrainPlanEmployeeTargetPojo>)session.getAttribute("duty_outing_target");
		}
		if(employeeTargetPojos == null || employeeTargetPojos.size() <= 0){
			return ERROR;
		}
		// 保存数据
		plan.setAuditStatus(AuditStatus.wait_audit);
		plan.setCloseAuditStatus(AuditStatus.wait_audit);
		try {
			// 保存培训计划内容
			trainPlanService.save(plan);
			// 获取planId
			// 保存培训对象内容
			trainPlanEmployeeTargetService
					.deleteTrainPlanEmployeeTargetByPlanId(plan.getId());

			/*JSONArray jsonArray = JSONArray.fromObject(jsonEmployeeTargets);
			if (jsonArray != null && jsonArray.size() > 0) {
				for (int i = 0; i < jsonArray.size(); i++) {
					TrainPlanEmployeeTarget employeeTarget = new TrainPlanEmployeeTarget();
					employeeTarget.setTrainPlan(plan);
					employeeTarget.setDuty(dutyService.get(jsonArray
							.getJSONObject(i).getLong("dutyId")));
					employeeTarget.setOrganization(organizationService
							.get(jsonArray.getJSONObject(i).getLong(
									"organizationId")));
					// dutyTarget.setCredit(Float.parseFloat(jsonArray.getJSONObject(i).getString("credit")));
					employeeTarget.setEmployeeinfoWork(employeeService
							.getEmployeeinfoWork(jsonArray.getJSONObject(i)
									.getLong("workId")));
					trainPlanEmployeeTargetService.save(employeeTarget);
				}
			}
			// 请Cookie
			Cookie[] cookies = ServletActionContext.getRequest().getCookies();
			if (cookies != null && cookies.length > 0) {
				for (Cookie mCookie : cookies) {
					if (mCookie.getName().equals("dutytarget")) {
						mCookie.setValue("");
					}
				}
			}*/
			if (employeeTargetPojos != null && employeeTargetPojos.size() > 0) {
				Iterator<TrainPlanEmployeeTargetPojo> it = employeeTargetPojos.iterator();
				while(it.hasNext()){
					TrainPlanEmployeeTargetPojo employeeTargetPojo = it.next();
					TrainPlanEmployeeTarget employeeTarget = new TrainPlanEmployeeTarget();
					employeeTarget.setTrainPlan(plan);
					employeeTarget.setOrganization(organizationService.get(employeeTargetPojo.getOrganizationId()));
					employeeTarget.setDuty(dutyService.get(employeeTargetPojo.getDutyId()));
					employeeTarget.setEmployeeinfoWork(employeeService.getEmployeeinfoWork(employeeTargetPojo.getWorkId()));
					
					trainPlanEmployeeTargetService.save(employeeTarget);
				}
			}
			session.removeAttribute("duty_outing_target");
		} catch (Exception e) {
			log.error(e);
			return ERROR;
		}
		return "main";
	}

	/**
	 * 删除培训计划
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/train/outing_train_delete", results = { @Result(name = "success", type = "plainText") })
	public String deletePlan() throws Exception {
		if (StringUtils.isNotBlank(ids)) {
			try {
				// 删除培训对象
				trainPlanEmployeeTargetService
						.deleteTrainPlanEmployeeTargetByPlanIds(ids);
				// 删除培训资源
				for (String s : ids.split(",")) {
					List<TrainMaterResource> list = trainMaterResourceService
							.getTrainMaterResourcesByPlanId(Long.parseLong(s),
									null, null);
					for (TrainMaterResource trainMaterResource : list) {
						File f = new File(ServletActionContext.getRequest()
								.getRealPath(
										trainMaterResource.getCoursewareUrl()));
						if (f.exists()) {
							f.delete();
						}
					}
				}
				// 删除培训计划
				trainPlanService.deleteTrainPlan(ids);
			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error(e.getMessage());
				}
				return ERROR;
			}

		}

		return SUCCESS;
	}

	/**
	 * 培训计划申请审核处理
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/train/outing_train_audit")
	public String handleTrainPlanAuditing() throws Exception {

		if (planId == null) {
			return ERROR;
		}
		try {

			plan = trainPlanService.getTrainPlan(planId);
			if (plan == null) {
				return ERROR;
			}

			employeeTargets = trainPlanEmployeeTargetService
					.getTrainPlanEmployeeTargets(plan.getId(), null, null);

			audits = trainPlanService.searchTrainPlanAuditings(plan.getId(),
					null, null);
			if (audits == null || audits.isEmpty()) {
				trainPlanService.saveTrainPlanAuditingProcess(plan, 1);
				audits = trainPlanService.searchTrainPlanAuditings(
						plan.getId(), null, null);
			}
            //检查当前登录用户是否可以审核当前结点
            if(audits != null && !audits.isEmpty()){
                checkCanAudit((Duty)null, audits.get(audits.size()-1));
            }
		} catch (Exception e) {
			e.printStackTrace(); // To change body of catch statement use File |
			// Settings | File Templates.
			throw new RuntimeException(e.getMessage());
		}
		currentAuditType = AuditType.audit_train_plan_outing.toString();
		return "outing_train_audit";
	}

	// ---------------外训结案------------------
	@Action("/train/outing_close_audit_main")
	public String executePlanCloseAudit() throws Exception {
		listTitle = "外训结案审核";
		listAction = "/train/outing_train_close_list_audit.xhtml";
		organizations = organizationService
				.findChildren(null, true, null, null);
		if (organizations != null && organizations.size() > 0) {
			if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
			organizationId = organizations.get(0).getId();
		}
		showChildOrg = true;
		return "main";
	}

	@Action("/train/outing_train_close_list_audit")
	public String dispatchPlanCloseAuditList() {
		listAction = "/train/outing_train_close_list_audit.xhtml";
		plans = trainPlanService.getTrainPlans(organizationId, dutyId, 1, null,
				createLimit(), createSorter());
		paging(plans);
		/* 设置翻页action */
		this.setPageUrl("train/outing_train_close_list_audit.xhtml");
		return "outing_train_close_list_audit";
	}

	@Action("/train/outing_train_close_audit")
	public String handleTrainPlanCloseAuditing() throws Exception {

		if (planId == null) {
			return ERROR;
		}
		try {

			plan = trainPlanService.getTrainPlan(planId);
			if (plan == null) {
				return ERROR;
			}

			employeeTargets = trainPlanEmployeeTargetService
					.getTrainPlanEmployeeTargets(plan.getId(), null, null);

			outingAudits = trainPlanService.searchTrainPlanCloseAuditings(
					plan.getId(), null, null);
			if (outingAudits == null || outingAudits.isEmpty()) {
				trainPlanService.saveTrainPlanAuditingProcess(plan, 1);
				outingAudits = trainPlanService.searchTrainPlanCloseAuditings(
						plan.getId(), null, null);
			}
            //检查当前登录用户是否可以审核当前结点
            if(outingAudits != null && !outingAudits.isEmpty()){
                checkCanAudit((Duty)null, outingAudits.get(outingAudits.size()-1));
            }
		} catch (Exception e) {
			e.printStackTrace(); // To change body of catch statement use File |
			// Settings | File Templates.
			throw new RuntimeException(e.getMessage());
		}
		currentAuditType = AuditType.audit_train_outing_plan_close.toString();
		return "outing_train_close_audit";
	}

	public void setOrganizations(List<Organization> organizations) {
		this.organizations = organizations;
	}

	public List<Organization> getOrganizations() {
		return organizations;
	}

	public LimitedList<TrainPlan> getPlans() {
		return plans;
	}

	public void setPlans(LimitedList<TrainPlan> plans) {
		this.plans = plans;
	}

	public LimitedList<TrainCategory> getCategories() {
		return categories;
	}

	public void setCategories(LimitedList<TrainCategory> categories) {
		this.categories = categories;
	}

	public LimitedList<TrainLecturer> getLecturers() {
		return lecturers;
	}

	public void setLecturers(LimitedList<TrainLecturer> lecturers) {
		this.lecturers = lecturers;
	}

	public LimitedList<TrainClassroom> getClassrooms() {
		return classrooms;
	}

	public void setClassrooms(LimitedList<TrainClassroom> classrooms) {
		this.classrooms = classrooms;
	}

	public TrainPlan getPlan() {
		return plan;
	}

	public void setPlan(TrainPlan plan) {
		this.plan = plan;
	}

	public Long getPlanId() {
		return planId;
	}

	public void setPlanId(Long planId) {
		this.planId = planId;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public Long getDutyId() {
		return dutyId;
	}

	public void setDutyId(Long dutyId) {
		this.dutyId = dutyId;
	}

	public Duty getDuty() {
		return duty;
	}

	public void setDuty(Duty duty) {
		this.duty = duty;
	}

	public LimitedList<EmployeeinfoWork> getWorks() {
		return works;
	}

	public void setWorks(LimitedList<EmployeeinfoWork> works) {
		this.works = works;
	}

	public EmployeeService getEmployeeService() {
		return employeeService;
	}

	public LimitedList<TrainPlanEmployeeTarget> getEmployeeTargets() {
		return employeeTargets;
	}

	public void setEmployeeTargets(
			LimitedList<TrainPlanEmployeeTarget> employeeTargets) {
		this.employeeTargets = employeeTargets;
	}

	public List<List<TrainPlanAuditing>> getAudits() {
		return audits;
	}

	public void setAudits(List<List<TrainPlanAuditing>> audits) {
		this.audits = audits;
	}

	public List<List<TrainOutingPlanCloseAuditing>> getOutingAudits() {
		return outingAudits;
	}

	public void setOutingAudits(
			List<List<TrainOutingPlanCloseAuditing>> outingAudits) {
		this.outingAudits = outingAudits;
	}

	public String getModule() {
		return module;
	}

	public void setModule(String module) {
		this.module = module;
	}

}
